"""
代码审查引擎模块
整合各种分析功能
"""
import logging
from typing import Dict, Any, Optional
from llm_integration import LLMService
from code_analyzer import CodeAnalyzer

logger = logging.getLogger(__name__)


class ReviewEngine:
    """代码审查引擎（整合各种分析功能）"""
    
    def __init__(self, llm_service: Optional[LLMService] = None):
        self.llm_service = llm_service or LLMService()
        self.code_analyzer = CodeAnalyzer(self.llm_service)
    
    async def comprehensive_review(
        self,
        code: str,
        language: str,
        context: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        综合代码审查
        
        Args:
            code: 代码内容
            language: 编程语言
            context: 代码上下文
        
        Returns:
            综合审查结果
        """
        try:
            # 并行执行多种分析
            quality_result = await self.code_analyzer.analyze_code(code, language, context)
            smells_result = await self.llm_service.detect_code_smells(code, language)
            
            return {
                "quality": quality_result,
                "code_smells": smells_result,
                "summary": self._generate_summary(quality_result, smells_result)
            }
        except Exception as e:
            logger.error(f"综合审查失败: {str(e)}")
            return {
                "error": f"综合审查失败: {str(e)}"
            }
    
    def _generate_summary(self, quality_result: Dict, smells_result: Dict) -> str:
        """
        生成审查摘要
        
        Args:
            quality_result: 质量分析结果
            smells_result: 坏味道检测结果
        
        Returns:
            摘要文本
        """
        summary_parts = []
        
        if "error" not in quality_result:
            score = quality_result.get("score", 0)
            summary_parts.append(f"代码质量评分: {score}/100")
            
            issues_count = len(quality_result.get("issues", []))
            if issues_count > 0:
                summary_parts.append(f"发现 {issues_count} 个问题")
        
        if "error" not in smells_result:
            smells_count = len(smells_result.get("smells", []))
            if smells_count > 0:
                summary_parts.append(f"检测到 {smells_count} 个代码坏味道")
        
        return " | ".join(summary_parts) if summary_parts else "审查完成"

